package com.xmall.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)//jdbctype-varcher
@MappedTypes(String[].class)//javatype-要转换的类型，如数组【】
public class StringArrayHandler implements TypeHandler<String[]> {

        ObjectMapper objectMapper = new ObjectMapper();
    /*
    *setParameter方法 输入映射对应的方法
    * index : 占位符的序号
    * 第三个参数：输入映射提供的值
    * 核心：将第三个参数转化为字符串
    * */
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] integers, JdbcType jdbcType) throws SQLException {

        String value = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(index,value);
    }

    /*
    * getResult输出映射
    *先获得查询结果
    * String->Integer[]
    * clumeLable 查询结果类名
    *
    * resultset 包含查询结果
    * */

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String clumeLable) throws SQLException {

        //查询接果转化为String类型
        String result = resultSet.getString(clumeLable);
        //类型转换
        String[] integers = objectMapper.readValue(result, String[].class);
        return integers;
    }
//下面2个方法不会使用到，一般要写
    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        String[] integers = objectMapper.readValue(result, String[].class);
        return integers;
    }

    @SneakyThrows
    @Override
    public String[] getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        String[] integers = objectMapper.readValue(result, String[].class);
        return integers;
    }

}
